package com.winhxd.b2c.customer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.*;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.bo.CustomerRevenueBO;
import com.winhxd.b2c.common.domain.customer.bo.CustomerWalletBO;
import com.winhxd.b2c.common.domain.customer.condition.*;
import com.winhxd.b2c.common.domain.customer.enums.CustomerRevenueEnum;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.enums.WithdrawalsStatusEnum;
import com.winhxd.b2c.common.domain.customer.model.*;
import com.winhxd.b2c.common.domain.customer.vo.*;
import com.winhxd.b2c.common.domain.message.condition.MiniTemplateData;
import com.winhxd.b2c.common.domain.message.enums.MiniMsgTypeEnum;
import com.winhxd.b2c.common.domain.pay.condition.PayTransfersToWxChangeCondition;
import com.winhxd.b2c.common.domain.pay.vo.PayTransfersToWxChangeVO;
import com.winhxd.b2c.common.domain.store.condition.StoreUserInfoCondition;
import com.winhxd.b2c.common.domain.system.login.condition.BackStageCustomerInfoCondition;
import com.winhxd.b2c.common.domain.system.user.condition.CheckUserCondition;
import com.winhxd.b2c.common.domain.system.user.dto.SysUserDTO;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.domain.system.user.vo.UserInfo;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.pay.PayServiceClient;
import com.winhxd.b2c.common.feign.store.StoreUserInfoClient;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.util.DateUtil;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.common.util.MessageSendUtils;
import com.winhxd.b2c.customer.dao.*;
import com.winhxd.b2c.customer.service.CustomerRevenueService;
import com.winhxd.b2c.customer.service.CustomerService;
import com.winhxd.b2c.customer.service.InvitationRecordService;
import com.winhxd.b2c.customer.util.SendMsgUtil;
import com.winhxd.b2c.customer.util.TemplateData;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author chengyy
 * @Description: 小程序用户服务实现类
 * @date 2018/8/6 9:23
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    private static final Logger logger = LoggerFactory.getLogger(InvitationRecordServiceImpl.class);
    private static final String KEYWORD1 = "keyword1";
    private static final String KEYWORD2 = "keyword2";
    private static final String KEYWORD3 = "keyword3";
    private static final String KEYWORD4 = "keyword4";
    private static final String KEYWORD5 = "keyword5";
    private static final String KEYWORD6 = "keyword6";
    @Autowired
    private CustomerUserInfoMapper customerUserInfoMapper;

    @Autowired
    private StoreUserInfoClient storeUserInfoClient;
    @Autowired
    private PayServiceClient payServiceClient;
    @Autowired
    private MessageSendUtils messageServiceClient;

    @Autowired
    private InvitationRecordService invitationRecordService;

    @Autowired
    private Cache cache;

    @Autowired
    private CustomerWalletMapper customerWalletMapper;
    @Autowired
    private CustomerRevenueDetailMapper customerRevenueDetailMapper;
    @Autowired
    private CustomerIntegralDetailMapper customerIntegralDetailMapper;
    @Autowired
    private CustomerWithdrawalsMapper customerWithdrawalsMapper;
    @Autowired
    private CustomerRevenueService customerRevenueService;

    @Autowired
    private UserServiceClient userServiceClient;

    @Override
    public int modifyCustomerStatus(BackStageCustomerInfoCondition condition) {
        CustomerUserInfo record = new CustomerUserInfo();
        record.setId(condition.getCustomerId());
        record.setStatus(condition.getStatus());
        int line =  customerUserInfoMapper.updateByPrimaryKeySelective(record);
        //如果是添加黑名单则需要把token设置无效
        if(line == 1 && condition.getStatus() == 0){
            //如果加入黑名单成功直接将token值为无效
            CustomerUserInfo customerUserInfo = customerUserInfoMapper.selectByPrimaryKey(condition.getCustomerId());
            if(customerUserInfo != null){
                cache.del(CacheName.CUSTOMER_USER_INFO_TOKEN + customerUserInfo.getToken());
            }
        }
        return line;
    }

    @Override
    public List<CustomerUserInfoVO> findCustomerUserByIds(List<Long> ids) {
        return customerUserInfoMapper.selectCustomerUserByIds(ids);
    }

    @Override
    public List<CustomerUserInfoVO> findCustomerUserStoreByIds(List<Long> ids) {
        return customerUserInfoMapper.selectCustomerUserStoreByIds(ids);
    }

    @Override
    public CustomerOperationHomePageVO findOperationHomePage() {
        CustomerOperationHomePageVO vo = new CustomerOperationHomePageVO();
        CustomerOperationHomePageCondition condition = new CustomerOperationHomePageCondition();
        //今日新增店长统计（二级分销商）
        condition.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode());
        condition.setNowDatetime(new Date());
        condition.setTodayStartTime(DateUtil.getStartDate(new Date()));
        int todayNewManager = customerUserInfoMapper.countTodayNewUser(condition);
        //今日新增会员统计
        condition.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode());
        int todayNewMembers = customerUserInfoMapper.countTodayNewUser(condition);
        vo.setTodayNewManager(todayNewManager);
        vo.setTodayNewMembers(todayNewMembers);
        return vo;
    }

    /**
     * 创建店铺
     * @param customerUserInfo
     * @return
     */
    @Override
    public CustomerUserInfoSimpleVO saveCustomerStoreOpne(CustomerUserInfo customerUserInfo) {
        CustomerUserInfoSimpleVO vo = new CustomerUserInfoSimpleVO();
        StoreUserInfoCondition storeUserInfoRegCondition = new StoreUserInfoCondition();
        storeUserInfoRegCondition.setStoreCustomerId(customerUserInfo.getId());
        storeUserInfoRegCondition.setStoreName(customerUserInfo.getNickName()+"的小店");
        Short status=0;
        storeUserInfoRegCondition.setStoreStatus(status);
        storeUserInfoClient.saveStoreUserInfo(storeUserInfoRegCondition);
        vo.setCustomerId(customerUserInfo.getId());
        return vo;
    }

    @Override
    public Boolean saveSystemUser(CustomerUserInfo customerUserInfo,SysUser parentSysUser,Long id,String operationName) {
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setParentId(parentSysUser.getParentId());
        sysUserDTO.setLevel(customerUserInfo.getLevel());
        sysUserDTO.setAccount(customerUserInfo.getCustomerMobile());
        sysUserDTO.setMobile(customerUserInfo.getCustomerMobile());
        sysUserDTO.setOrgId(parentSysUser.getOrgId());
        sysUserDTO.setRoleId(parentSysUser.getRoleId());
        sysUserDTO.setUsername(customerUserInfo.getNickName()==null?customerUserInfo.getWechatName():customerUserInfo.getNickName());
        Short status=1;
        sysUserDTO.setStatus(status);
        UserInfo user= new UserInfo();
        user.setId(id);
        user.setUsername(operationName);
        user.setCustomerId(customerUserInfo.getId());
        sysUserDTO.setUserInfo(user);
        logger.info("创建后台登录账号！{}",customerUserInfo.getCustomerMobile());
        ResponseResult<Long> responseResult = userServiceClient.saveSysUser(sysUserDTO);
        if(responseResult.getCode()!=0){
            return false;
        }
        return responseResult.getData()!=null;
    }

    @Override
    public void updateSystemUser(CustomerUserInfo customerUserInfo) {
        SysUser sysUser;
        CheckUserCondition condition = new CheckUserCondition();
        condition.setCustomerId(customerUserInfo.getId());
        ResponseResult<SysUser> result = userServiceClient.getSysUserByCondition(condition);
        if(result.getCode()!=0){
            throw new BusinessException(BusinessCode.CODE_1001);
        }
        sysUser=result.getData();
        sysUser.setAccount(customerUserInfo.getCustomerMobile());
        sysUser.setMobile(customerUserInfo.getCustomerMobile());
        sysUser.setUpdatedBy(customerUserInfo.getId());
        sysUser.setUpdatedByName(customerUserInfo.getNickName()==null?customerUserInfo.getWechatName():customerUserInfo.getNickName());
        logger.info("修改后台用户手机号和账号：{}",JsonUtil.toJSONString(customerUserInfo));
        userServiceClient.modifySysUser(sysUser);
    }

    @Override
    public void modifyCustomerParentIdById(InvitationRecordCondition condition) {
        List<CustomerInvitationRecord> recordVOList = invitationRecordService.findInvitationRecord(condition);
        CustomerParentIdCondition conditionParent = new CustomerParentIdCondition();
        List<Long> custList = new ArrayList<>();
        recordVOList.forEach(v -> {
            if(null!=v.getSlaveId()) {
                custList.add(v.getSlaveId());
            }
        });
        CustomerUserInfo customerUserInfo = customerUserInfoMapper.selectByPrimaryKey(condition.getMasterId());
        conditionParent.setCustomerList(custList);
        conditionParent.setChannelId(customerUserInfo.getChannelId());
        conditionParent.setParentId(condition.getMasterId());
        conditionParent.setBindTime(new Date());
        if(!custList.isEmpty() && null!=condition.getMasterId()) {
            customerUserInfoMapper.updateCustomerParentIdByIds(conditionParent);
        }
    }

    @Override
    public CustomerTotalVO getCustomerTotalById(CustomerTotalCondition condition) {
        CustomerTotalVO vo = new CustomerTotalVO();

        //今日访问会员数量
        String key =  CustomerConstant.USER_TODAY_VISIT_COUNT+condition.getCustomerId();
        int count=0;
        if(cache.exists(key)){
           count = cache.hgetAll(key).size();
        }
        vo.setTodayVisitTotal(count);

        //统计新会员
        condition.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode());
        Date startDate= DateUtil.getStartDate(new Date());
        condition.setStartTime(startDate);
        Integer newUserCount = customerUserInfoMapper.selectCustomerTodayTotal(condition);
        vo.setNewUserTotal(newUserCount==null?0:newUserCount);

        //统计老会员
        Date endDate=DateUtil.getEndDate(new Date(),-1);
        condition.setStartTime(null);
        condition.setEndTime(endDate);
        Integer oldUserCount = customerUserInfoMapper.selectCustomerTodayTotal(condition);
        vo.setOldUserTotal(oldUserCount==null?0:oldUserCount);
        logger.info("统计会员基本信息：{}----{}",JsonUtil.toJSONString(vo),condition.getCustomerId());
        return vo;
    }

    @Override
    public List<CustomerBaseCollectVO> findCustomerWallet(CustomerWalletCondition condition) {
        if (condition == null || CollectionUtils.isEmpty(condition.getIds())) {
            return Collections.emptyList();
        }
        List<CustomerWalletBO> walletList = new ArrayList<>();
        condition.getIds().stream().forEach(id ->{
            CustomerWalletBO bo = new CustomerWalletBO();
            CustomerUserInfo customerUserInfo = customerUserInfoMapper.selectByPrimaryKey(id);
            if (null != customerUserInfo) {
                bo.setId(customerUserInfo.getId());
                bo.setLevel(customerUserInfo.getLevel() == 0 ? CustomerRevenueEnum.LEVEL_VIP.getStatus() : CustomerRevenueEnum.LEVEL_AGENT.getStatus());
                walletList.add(bo);
            }
        });
        return customerWalletMapper.findCustomerWallet(walletList);
    }

    @Override
    public PagedList<CustomerRevenueDetailVO> getUserRevenueDetail(CustomerRevenueDetailCondition condition) {
        PagedList<CustomerRevenueDetailVO> pagedList = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<CustomerRevenueDetailVO> detailVO = customerRevenueDetailMapper.getUserRevenueDetail(condition);
        PageInfo<CustomerRevenueDetailVO> pageInfo = new PageInfo<>(detailVO);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(pageInfo.getPageNum());
        pagedList.setPageSize(pageInfo.getPageSize());
        pagedList.setTotalRows(pageInfo.getTotal());
        return pagedList;
    }

    @Override
    public PagedList<CustomerIntegralDetailVO> getUserIntegralDetail(CustomerIntegralDetailCondition condition) {
        PagedList<CustomerIntegralDetailVO> pagedList = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<CustomerIntegralDetailVO> detailVO = customerIntegralDetailMapper.getUserIntegralDetail(condition);
        PageInfo<CustomerIntegralDetailVO> pageInfo = new PageInfo<>(detailVO);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(pageInfo.getPageNum());
        pagedList.setPageSize(pageInfo.getPageSize());
        pagedList.setTotalRows(pageInfo.getTotal());
        return pagedList;
    }

    @Override
    public PagedList<CustomerWithdrawalsVO> findPayWithdrawals(CustomerWithdrawalsCondition condition) {
        PagedList<CustomerWithdrawalsVO> pagedList = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<CustomerWithdrawalsVO> detailVO = customerWithdrawalsMapper.findPayWithdrawals(condition);
        PageInfo<CustomerWithdrawalsVO> pageInfo = new PageInfo<>(detailVO);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(pageInfo.getPageNum());
        pagedList.setPageSize(pageInfo.getPageSize());
        pagedList.setTotalRows(pageInfo.getTotal());
        return pagedList;
    }

    @Override
    public Integer getWithdrawDepositNum() {
        return customerWithdrawalsMapper.selectWithdrawDepositNum();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer auditPayWithdrawals(CustomerAuditCondition condition) {
        logger.info("CustomerServiceImpl -> auditPayWithdrawals操作人信息：{}" + JsonUtil.toJSONString(condition));
        CustomerWithdrawals withdrawals = customerWithdrawalsMapper.selectByPrimaryKey(condition.getId());
        withdrawals.setId(condition.getId());
        withdrawals.setUpdated(new Date());
        withdrawals.setUpdatedBy(condition.getId());
        withdrawals.setUpdatedByName(condition.getUpdatedByName());
        withdrawals.setAuditStatus((short) 1);
        PayTransfersToWxChangeCondition toWxChangeCondition = new PayTransfersToWxChangeCondition();
        toWxChangeCondition.setPartnerTradeNo(withdrawals.getWithdrawalsNo());
        toWxChangeCondition.setAccountId(withdrawals.getPaymentAccount());
        toWxChangeCondition.setAccountName(withdrawals.getName());
        toWxChangeCondition.setDesc("原译平台");
        toWxChangeCondition.setTotalAmount(withdrawals.getTotalFee());
        toWxChangeCondition.setSpbillCreateIp(withdrawals.getSpbillCreateIp() == null ? "127.0.0.1" : withdrawals.getSpbillCreateIp());
        toWxChangeCondition.setOperaterID(Objects.toString(condition.getId(),null));
        logger.info("CustomerServiceImpl -> auditPayWithdrawals调用pay-microservice入参：{}" + JsonUtil.toJSONString(toWxChangeCondition));
        PayTransfersToWxChangeVO dataWithException = payServiceClient.transfersToChange(toWxChangeCondition).getDataWithException();
        logger.info("CustomerServiceImpl -> auditPayWithdrawals调用pay-microservice出参：{}" + JsonUtil.toJSONString(dataWithException));
        if (dataWithException.isTransfersResult()) {
            withdrawals.setCallbackStatus(WithdrawalsStatusEnum.SUCCESS.getStatusCode());
        } else {
            //是否需要用户重新申请提现流程，
            if (dataWithException.isAbleContinue()) {
                // 提现失败，后台可以再审核
                withdrawals.setAuditStatus((short) 0);
                withdrawals.setCallbackStatus(WithdrawalsStatusEnum.FAIL.getStatusCode());
            } else {
                // 提现无效，置为不通过，退款
                withdrawals.setAuditStatus((short) 2);
                withdrawals.setCallbackStatus(WithdrawalsStatusEnum.INVALID.getStatusCode());
            }
        }
        //C端展示提现失败原因
        if (dataWithException.getErrorCode() != null) {
            if(dataWithException.getErrorCode().equals(TransfersToWxError.MONEY_LIMIT.getCode())){
                withdrawals.setErrorMessage("当日累积限额超过2万，请重新提现。");
            } else if (dataWithException.getErrorCode().equals(TransfersToWxError.V2_ACCOUNT_SIMPLE_BAN.getCode())) {
                withdrawals.setErrorMessage("请至微信实名认证后再次提现");

            } else if (dataWithException.getErrorCode().equals(TransfersToWxError.PARAM_ERROR.getCode())) {
                //TODO 提示文案信息
                withdrawals.setErrorMessage("");
            }
        }
        withdrawals.setCallbackReason(dataWithException.getErrorDesc());
        withdrawals.setTransactionId(dataWithException.getPaymentNo());
        withdrawals.setTimeEnd(dataWithException.getPaymentTime());
        int result = customerWithdrawalsMapper.updateByPrimaryKey(withdrawals);
        // 流水记录
        this.transfersPublic(withdrawals);
        // 消息推送
        this.sendMsg(dataWithException, withdrawals);
        return result;
    }

    /**
     * 消息推送
     * @param dataWithException
     * @param withdrawals
     */
    private void sendMsg(PayTransfersToWxChangeVO dataWithException, CustomerWithdrawals withdrawals) {
        //成功推送消息
        if (dataWithException.isTransfersResult()) {
            logger.info("CustomerServiceImpl -> auditPayWithdrawals提现成功发送消息开始执行...");
            this.sendSmsMsg(withdrawals, null);
            this.sendMiniTemplateMsg(withdrawals, null);
        } else {
            // 失败推送消息
            logger.info("CustomerServiceImpl -> auditPayWithdrawals提现失败发送消息开始执行...errorCode：{}" + dataWithException.getErrorCode());
            this.sendSmsMsg(withdrawals, dataWithException.getErrorCode());
            this.sendMiniTemplateMsg(withdrawals, dataWithException.getErrorCode());
        }
    }


    /**
     * 发送短信
     * @param errorCode
     * @param withdrawals
     */
    private void sendSmsMsg(CustomerWithdrawals withdrawals, String errorCode){
        Calendar cal = Calendar.getInstance();
        cal.setTime(withdrawals.getCreated());
        int month=cal.get(Calendar.MONTH)+1;
        int day=cal.get(Calendar.DATE);
        String notifyMsg = "";
        if (null != errorCode) {
            if (TransfersToWxError.MONEY_LIMIT.getCode().equals(errorCode)) {
                notifyMsg = PayNotifyMsg.STORE_MONEY_FAIL_WITHDRWAL.replace("mm",String.valueOf(month)).replace("dd",String.valueOf(day));
            }
            if (TransfersToWxError.V2_ACCOUNT_SIMPLE_BAN.getCode().equals(errorCode)) {
                notifyMsg = PayNotifyMsg.STORE_FAIL_WITHDRWAL.replace("mm",String.valueOf(month)).replace("dd",String.valueOf(day));
            }
        } else {
            notifyMsg = PayNotifyMsg.STORE_SUCCESS_WITHDRWAL.replace("mm",String.valueOf(month)).replace("dd",String.valueOf(day));

        }
        SendMsgUtil.sendSmsMsg(messageServiceClient,withdrawals.getMobile(),notifyMsg);
    }

    /**
     * 发送小程序模板
     * @param withdrawals
     */
    private void sendMiniTemplateMsg(CustomerWithdrawals withdrawals, String errorCode) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(withdrawals.getCreated());
        int month=cal.get(Calendar.MONTH)+1;
        int day=cal.get(Calendar.DATE);
        Short msgType = MiniMsgTypeEnum.WITHDRAWAL_AUDIT.getMsgType();
        List<MiniTemplateData> temData = new ArrayList<>();
        if (null != errorCode) {
            msgType = MiniMsgTypeEnum.WITHDRAWAL_APPLE.getMsgType();
            if (TransfersToWxError.MONEY_LIMIT.getCode().equals(errorCode)) {
                // 提现上限发送消息
                temData = TemplateData.New().add(KEYWORD1, withdrawals.getTotalFee().toString())
                        .add(KEYWORD2, getFormatDate(withdrawals.getCreated()))
                        .add(KEYWORD3, "未通过").add(KEYWORD4, getFormatDate(withdrawals.getTimeEnd()))
                        .add(KEYWORD5, PayNotifyMsg.STORE_MONEY_FAIL_WITHDRWAL.replace("mm",String.valueOf(month)).replace("dd",String.valueOf(day)))
                        .getData();
            }
            if (TransfersToWxError.V2_ACCOUNT_SIMPLE_BAN.getCode().equals(errorCode)) {
                // 未实名认证发送消息
                temData = TemplateData.New().add(KEYWORD1, withdrawals.getTotalFee().toString())
                        .add(KEYWORD2, getFormatDate(withdrawals.getCreated()))
                        .add(KEYWORD3, "未通过").add(KEYWORD4, getFormatDate(withdrawals.getTimeEnd()))
                        .add(KEYWORD5, PayNotifyMsg.STORE_FAIL_WITHDRWAL.replace("mm",String.valueOf(month)).replace("dd",String.valueOf(day)))
                        .getData();
            }
        } else {
            temData = TemplateData.New().add(KEYWORD1, withdrawals.getTotalFee().toString())
                    .add(KEYWORD2, getFormatDate(withdrawals.getCreated()))
                    .add(KEYWORD3, "已通过").add(KEYWORD4, getFormatDate(withdrawals.getUpdated()))
                    .add(KEYWORD5, "预计"+getFormatDate(new Date(withdrawals.getUpdated().getTime() + 2 * 60 * 60 * 1000))+"到账，请注意查收！")
                    .getData();
            // 审核通过发送消息
            SendMsgUtil.sendMiniTemplateMsg(messageServiceClient, withdrawals.getBuyerId(), null, msgType, null, temData);
            // 提现成功发送消息
            msgType = MiniMsgTypeEnum.WITHDRAWAL_SUCCESS.getMsgType();
            BigDecimal mal = withdrawals.getTotalFee().subtract(withdrawals.getCmmsAmt());
            temData = TemplateData.New().add(KEYWORD1, withdrawals.getTotalFee().toString()).add(KEYWORD2, withdrawals.getCmmsAmt().toString())
                    .add(KEYWORD3, mal.toString()).add(KEYWORD4, "实时到账").add(KEYWORD5, "微信钱包").add(KEYWORD6, "请注意查收").getData();

        }
        SendMsgUtil.sendMiniTemplateMsg(messageServiceClient, withdrawals.getBuyerId(), null, msgType, null, temData);
    }

    /**
     * 提现结果记录
     * @param withdrawals
     */
    private void transfersPublic(CustomerWithdrawals withdrawals){
        logger.info("CustomerServiceImpl -> auditPayWithdrawals:transfersPublic提现结果记录开始执行...状态:{}" + withdrawals.getCallbackStatus());
        CustomerUserInfo customerUserInfo = customerUserInfoMapper.selectByPrimaryKey(withdrawals.getCustomerId());
        Byte revenueLevel = CustomerRevenueServiceImpl.getRevenueLevel(customerUserInfo.getLevel());
        Integer level = Objects.isNull(revenueLevel) ? null : Integer.valueOf(revenueLevel);
        CustomerWallet customerWallet = customerWalletMapper.selectByCustomerIdAndLevel(withdrawals.getCustomerId(), level);
        if(WithdrawalsStatusEnum.SUCCESS.getStatusCode() == withdrawals.getCallbackStatus()){
            // 提现成功：提现次数累加1次
            customerWallet.setWithdrawNumber(customerWallet.getWithdrawNumber() == null ? 1 : customerWallet.getWithdrawNumber()+1);
            customerWallet.setUpdated(new Date());
            customerWalletMapper.updateByPrimaryKey(customerWallet);

            // 成功记录用户收益 customer_revenue_detail
            CustomerRevenueDetail revenueDetail = new CustomerRevenueDetail();
            revenueDetail.setCustomerId(withdrawals.getCustomerId());
            revenueDetail.setType(CustomerRevenueEnum.TYPE_OUT.getStatus());
            BigDecimal totalFee = withdrawals.getTotalFee().add(withdrawals.getCmmsAmt() == null ? new BigDecimal(0) : withdrawals.getCmmsAmt());
            revenueDetail.setAmount(totalFee.multiply(new BigDecimal(-1)));
            revenueDetail.setCreated(new Date());
            customerRevenueDetailMapper.insertSelective(revenueDetail);
        }
        // 提现失败：退款；成功流水记录到提现表
        if(WithdrawalsStatusEnum.INVALID.getStatusCode() == withdrawals.getCallbackStatus()){
            customerWallet.setUpdated(new Date());
            BigDecimal cmmsAmt = withdrawals.getCmmsAmt() == null ? new BigDecimal(0) : withdrawals.getCmmsAmt();
            customerWallet.setBalance(customerWallet.getBalance().add(withdrawals.getTotalFee().add(cmmsAmt)));
            customerWallet.setWithdraw(customerWallet.getWithdraw().subtract(withdrawals.getTotalFee().add(cmmsAmt)));
            customerWalletMapper.updateByPrimaryKey(customerWallet);

            // 更新缓存
            CustomerRevenueBO revenueBO = customerRevenueService.getCustomerRevenueCache(withdrawals.getCustomerId(), customerUserInfo.getLevel());
            if (null != revenueBO) {
                revenueBO.setBalance(customerWallet.getBalance().add(withdrawals.getTotalFee().add(cmmsAmt)));
                revenueBO.setWithdraw(customerWallet.getWithdraw().subtract(withdrawals.getTotalFee().add(cmmsAmt)));
                customerRevenueService.modifyCustomerRevenueCache(withdrawals.getCustomerId(), customerUserInfo.getLevel(), revenueBO);
            }
        }
    }
    @Override
    public int countCheckMobileNumber( Long id, String mobile){
        return customerUserInfoMapper.countCheckMobileNumber(id,mobile);
    }

    private String getFormatDate(Date date) {
        return new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(date);
    }
}
